//
//  JWAddressBookContactsVC.m
//  jinwang
//
//  Created by jzb on 2018/3/28.
//  Copyright © 2018年 jzb. All rights reserved.
//

#import "JWAddressBookContactsVC.h"
#import "JWAddressBookContactsCell.h"
#import "JWAddressBookContactsModel.h"
#import "UserMessageVC.h"

@interface JWAddressBookContactsVC ()

@property (nonatomic,strong) JWAddressBookContactsCell *cell;
//@property (nonatomic,strong) BJDynamicSnapshotModel *Listmodel;
@property (nonatomic,strong) NSMutableArray *ListmodelArr;
//索引
@property (nonatomic,strong) NSMutableArray *titleArray;

@end

@implementation JWAddressBookContactsVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setUpTableView];
    [self makeUrl_batchFriends];

}
//配置tableView
-(void)setUpTableView{
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.tableView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    //注册cell
    
    [self registerCellWithCellClassArray:@[NSStringFromClass([JWAddressBookContactsCell class])]];
    
    //索引
//    [self.tableView setSectionIndexBackgroundColor:[UIColor clearColor]];//索引条的颜色
    self.tableView.sectionIndexBackgroundColor = [UIColor clearColor];
    [self.tableView setSectionIndexTrackingBackgroundColor:[UIColor clearColor]];//选中时，索引条的颜色
    [self.tableView setSectionIndexColor:[UIColor grayColor]];//索引条文字的颜色
}
#pragma mark -UITableViewDelegate,UITableViewDataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.ListmodelArr.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSArray *arr = self.ListmodelArr[section];
    return arr.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    self.cell = [tableView dequeueReusableCellWithIdentifier:[JWAddressBookContactsCell getCellReuseIdentifier]];
    self.cell.contentView.backgroundColor = [UIColor clearColor];

    NSArray *arr = self.ListmodelArr[indexPath.section];
    JWAddressBookContactsModel *model = arr[indexPath.row];
    self.cell.model = model;
    
    return self.cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 61;
}
#pragma mark -索引
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 20;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.1;
}
-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 20)];
    view.backgroundColor = kRGBColor(245, 245, 245);
    UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(10, 3, tableView.frame.size.width-20, 14)];
    label.backgroundColor = [UIColor clearColor];
    label.textAlignment = NSTextAlignmentLeft;
    label.font = [UIFont systemFontOfSize:15];
    label.textColor = [UIColor colorWithRed:130/255.0 green:130/255.0 blue:130/255.0 alpha:1];
    NSString * title = self.titleArray[section];
    label.text = title;
    [view addSubview:label];
    return view;
}
//返回索引数组
-(NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView{
    return self.titleArray;
}
//响应点击索引时的委托方法
-(NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index{
    NSLog(@"===%@  ===%ld",title,(long)index);
    //点击索引，列表跳转到对应索引的行
    __block typeof(self) weakSelf = self;
    [self.ListmodelArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSArray *arr = (NSArray *)obj;
        JWAddressBookContactsModel *model = arr[0];
        NSString *initial = model.initial;
//        NSString *pinYin = name.pinyinString;
//        NSString *firstChat = [pinYin substringToIndex:1];
        NSString *bigChat = [initial uppercaseString];//大写字母
        if ([title isEqualToString:bigChat]) {
            [weakSelf.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:idx]
                                            animated:YES
                                      scrollPosition:UITableViewScrollPositionTop];
        }
    }];
    //弹出首字母提示
//    [MBProgressHUD showInfoMessage:title];
    
    return index;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSArray *arr = self.ListmodelArr[indexPath.section];
    JWAddressBookContactsModel *model = arr[indexPath.row];
    UserMessageVC *vc = [UserMessageVC new];
    vc.user_id = [NSString stringWithFormat:@"%@",model.user_id];
    vc.VC_Type = @"good_friend";
    [self.navigationController pushViewController:vc animated:YES];
    
}


#pragma mark -懒加载
-(NSMutableArray *)ListmodelArr{
    if (!_ListmodelArr) {
        _ListmodelArr = [NSMutableArray array];
    }
    return _ListmodelArr;
}
-(NSMutableArray *)titleArray{
    if (!_titleArray) {
        _titleArray = [NSMutableArray array];
    }
    return _titleArray;
}
#pragma mark -网络请求
-(void)makeUrl_batchFriends{
    
    [[DDNetworkManagerDate makeUrl_batchFriends_index_with_token:k_user_token] post_RequestFinshSuccess:^(id responseObject) {
        
        NSLog(@"----->>%@",responseObject);
        if ([self requestFinshCode:responseObject isShowMessage:YES] == 1) {
            
            NSArray *data = [responseObject objectForKey:kRequsetDataKey];
            NSMutableArray *arr = [NSMutableArray array];
            [data enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                JWAddressBookContactsModel *model = [JWAddressBookContactsModel yy_modelWithDictionary:obj];
                [arr addObject:model];
            }];
//            self.ListmodelArr = arr.mutableCopy;
            self.ListmodelArr = [self sortBy_PinYin_with:[arr sortedWithChineseKey:@"initial"]].mutableCopy;
            
        }
        [self.tableView reloadData];
    } failure:^(id errorObject) {
        [self showBottomMessag:@"网络请求失败"];
    }];
}

//排序
-(NSMutableArray *)sortBy_PinYin_with:(NSArray *)arr{
    //将原来的数组变成装字典的数组@[@{a:model}, @{a:model, @{b:model},...]
    __block NSMutableArray *chatArr = [NSMutableArray array];
    [arr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        JWAddressBookContactsModel *model = (JWAddressBookContactsModel *)obj;
        
        NSString *initial = model.initial;
        
        NSDictionary *dic = @{initial:model};
        [self.titleArray addObject:initial];
        [chatArr addObject:dic];
    }];
//    NSMutableArray *kkkArr = [self sortObjectsAccordingToInitialWith:chatArr];
    //将相同首字母的放在一个数组里成为子数组
    NSMutableArray *modelArr = [@[] mutableCopy];
    for (int i = 0; i < chatArr.count; i++) {
        NSDictionary *dic = chatArr[i];
        NSString *string = dic.allKeys[0];
        NSMutableArray *tempArray = [@[] mutableCopy];
        JWAddressBookContactsModel *model = dic[string];
        [tempArray addObject:model];
        for (int j = i+1; j < chatArr.count; j++) {
            NSDictionary *jdic = chatArr[j];
            NSString *jstring = jdic.allKeys[0];
            JWAddressBookContactsModel *jmodel = jdic[jstring];
            if([string isEqualToString:jstring]){
                [tempArray addObject:jmodel];
                [chatArr removeObjectAtIndex:j];
                j -= 1;
            }
        }
        [modelArr addObject:tempArray];
    }
    return modelArr;
}

// 按首字母分组排序数组
-(NSMutableArray *)sortObjectsAccordingToInitialWith:(NSArray *)arr {
    
    // 初始化UILocalizedIndexedCollation
    UILocalizedIndexedCollation *collation = [UILocalizedIndexedCollation currentCollation];
    
    //得出collation索引的数量，这里是27个（26个字母和1个#）
    NSInteger sectionTitlesCount = [[collation sectionTitles] count];
    //初始化一个数组newSectionsArray用来存放最终的数据，我们最终要得到的数据模型应该形如@[@[以A开头的数据数组], @[以B开头的数据数组], @[以C开头的数据数组], ... @[以#(其它)开头的数据数组]]
    NSMutableArray *newSectionsArray = [[NSMutableArray alloc] initWithCapacity:sectionTitlesCount];
    
    //初始化27个空数组加入newSectionsArray
    for (NSInteger index = 0; index < sectionTitlesCount; index++) {
        NSMutableArray *array = [[NSMutableArray alloc] init];
        [newSectionsArray addObject:array];
    }
    
    //将每个名字分到某个section下
    for (JWAddressBookContactsModel *personModel in arr) {
        //获取name属性的值所在的位置，比如"林丹"，首字母是L，在A~Z中排第11（第一位是0），sectionNumber就为11
        NSInteger sectionNumber = [collation sectionForObject:personModel collationStringSelector:@selector(initial)];
        //把name为“林丹”的p加入newSectionsArray中的第11个数组中去
        NSMutableArray *sectionNames = newSectionsArray[sectionNumber];
        [sectionNames addObject:personModel];
    }
    
    //对每个section中的数组按照name属性排序
    for (NSInteger index = 0; index < sectionTitlesCount; index++) {
        NSMutableArray *personArrayForSection = newSectionsArray[index];
        NSArray *sortedPersonArrayForSection = [collation sortedArrayFromArray:personArrayForSection collationStringSelector:@selector(name)];
        newSectionsArray[index] = sortedPersonArrayForSection;
    }
    
    //    //删除空的数组
    //    NSMutableArray *finalArr = [NSMutableArray new];
    //    for (NSInteger index = 0; index < sectionTitlesCount; index++) {
    //        if (((NSMutableArray *)(newSectionsArray[index])).count != 0) {
    //            [finalArr addObject:newSectionsArray[index]];
    //        }
    //    }
    //    return finalArr;
    
    return newSectionsArray;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}


@end
